package com.ada.lbs.v3.service;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import com.ada.http.Connection;
import com.ada.http.Connection.Method;
import com.ada.http.HttpConnection;
import com.ada.lbs.v3.api.PoiApi;
import com.ada.lbs.v3.domain.Poi;
import com.ada.lbs.v3.domain.PoiDetailState;
import com.ada.lbs.v3.domain.State;
import com.google.gson.Gson;

public class PoiService implements PoiApi {

	String createurl = "http://api.map.baidu.com/geodata/v3/poi/create";
	String detailurl = "http://api.map.baidu.com/geodata/v3/poi/detail";

	@Override
	public State add(Poi poi) {
		State result = null;
		Connection connection = HttpConnection.connect(createurl);
		connection.data("address", poi.getAddress()).data("title",
				poi.getTitle());

		connection.data("ak", Config.AK);
		connection.data("geotable_id", Config.geotable_id);
		connection.data("latitude", "" + poi.getLatitude());
		connection.data("longitude", "" + poi.getLongitude());
		connection.data("coord_type", "" + poi.getCoord_type());
		Map<String, String> maps = poi.getData();
		if (maps.size() > 0) {

			Set<String> keys = maps.keySet();
			for (String string : keys) {
				connection.data(string, "" + maps.get(string));

			}
		}
		// connection.data("sn", ""+poi.getCoord_type());
		connection.method(Method.POST);
		String msg = null;
		try {
			msg = connection.execute().body();
			Gson gson = new Gson();
			result = gson.fromJson(msg, State.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (msg == null) {
		}
		return result;
	}

	public PoiDetailState findById(int id) {
		PoiDetailState result = null;
		Connection connection = HttpConnection.connect(detailurl);
		connection.data("ak", Config.AK);
		connection.data("geotable_id", Config.geotable_id);
		connection.data("id", "" + id);

		// connection.data("sn", ""+poi.getCoord_type());
		connection.method(Method.GET);
		String msg = null;
		try {
			msg = connection.execute().body();
			Gson gson = new Gson();
			result = gson.fromJson(msg, PoiDetailState.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (msg == null) {
		}
		return result;
	}
}
